package com.mall.module.user.controller;

import com.mall.common.result.Result;
import com.mall.common.util.SecurityUtils;
import com.mall.module.user.domain.dto.UserAddressDTO;
import com.mall.module.user.domain.vo.UserAddressVO;
import com.mall.module.user.service.UserAddressService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController
@Api(tags = "用户地址管理")
public class UserAddressController {

    @Autowired
    private UserAddressService userAddressService;

    /**
     * 获取用户地址列表
     */
    @GetMapping("/address/list")
    @ApiOperation(value = "获取用户地址列表")
    public Result<List<UserAddressVO>> listUserAddresses() {
        Long userId = SecurityUtils.getCurrentUserId();
        List<UserAddressVO> addresses = userAddressService.listUserAddresses(userId);
        return Result.success(addresses);
    }

    /**
     * 添加收货地址
     */
    @PostMapping("/address")
    @ApiOperation(value = "添加收货地址")
    public Result<Boolean> addUserAddress(@RequestBody @Valid UserAddressDTO addressDTO) {
        Long userId = SecurityUtils.getCurrentUserId();
        boolean result = userAddressService.addAddress(userId, addressDTO);
        return Result.success(result);
    }

    /**
     * 修改收货地址
     */
    @PutMapping("/address/{addressId}")
    @ApiOperation(value = "修改收货地址")
    @ApiImplicitParam(name = "addressId", value = "地址ID", required = true, dataType = "Long", paramType = "path")
    public Result<Boolean> updateUserAddress(@PathVariable Long addressId, @RequestBody @Valid UserAddressDTO addressDTO) {
        Long userId = SecurityUtils.getCurrentUserId();
        boolean result = userAddressService.updateAddress(userId, addressId, addressDTO);
        return Result.success(result);
    }


    /**
     * 删除收货地址
     */
    @DeleteMapping("/address/{addressId}")
    @ApiOperation(value = "删除收货地址")
    @ApiImplicitParam(name = "addressId", value = "地址ID", required = true, dataType = "Long", paramType = "path")
    public Result<Boolean> deleteUserAddress(@PathVariable Long addressId) {
        Long userId = SecurityUtils.getCurrentUserId();
        boolean result = userAddressService.deleteAddress(userId, addressId);
        return Result.success(result);
    }

    /**
     * 设置默认地址
     */
    @PutMapping("/address/{addressId}/default")
    @ApiOperation(value = "设置默认地址")
    @ApiImplicitParam(name = "addressId", value = "地址ID", required = true, dataType = "Long", paramType = "path")
    public Result<Boolean> setDefaultAddress(@PathVariable Long addressId) {
        Long userId = SecurityUtils.getCurrentUserId();
        boolean result = userAddressService.setDefaultAddress(userId, addressId);
        return Result.success(result);
    }
}